package xyj.sparrow.scheduler.server.service.impl;

import io.netty.channel.Channel;

import xyj.sparrow.common.connect.SparrowConnect;
import xyj.sparrow.common.netty.bean.Register;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import xyj.sparrow.scheduler.server.ClientManager;
import xyj.sparrow.scheduler.server.connect.ConnectManager;
import xyj.sparrow.scheduler.server.service.IRegisterService;
import xyj.sparrow.scheduler.util.ApplicationContextUtil;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;

/**
 * @author 江南小俊
 * @since 2021-06-15 12:53
 **/
//加注解进行服务暴
//@Component
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
    private final ConnectManager connectManager = ApplicationContextUtil.getBean(ConnectManager.class);

    /**
     * 客户端注册
     * AppId,TaskId,哪个类
     *
     * @param registers
     * @param channelHandlerContext
     * @return boolean
     * @author Jim
     * @since 2021/6/15 下午12:55
     **/

    @Override
    public String register(List<Register> registers, ChannelHandlerContext channelHandlerContext) {
        log.info("注册的服务数量：{}", registers.size());
        InetSocketAddress inetSocketAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
        for (Register register : registers) {
//            ClientManager.addClient(register.getAppId(), channelHandlerContext.channel());
            SparrowConnect connect = new SparrowConnect();
            connect.setAppId(register.getAppId());
            connect.setChannel(channelHandlerContext.channel());
            connect.setConnectDesc(inetSocketAddress.getAddress().getHostAddress() + ":" + inetSocketAddress.getPort());
            connectManager.addConnect(connect);
            ClientManager.addTaskClass(register.getTaskId(), register.getClassName());

        }
        return "注册的服务数量:" + registers.size();
    }
}
